package com.xdl.modules.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdl.common.constants.CommonConstants;
import com.xdl.common.utils.PasswordUtil;
import com.xdl.common.utils.SnowflakeIdUtil;
import com.xdl.common.utils.StringUtils;
import com.xdl.configuration.BaseContextHandler;
import com.xdl.modules.system.entity.*;
import com.xdl.modules.system.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xdl.modules.system.model.*;
import com.xdl.modules.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author iron guo
 * @since 2022-03-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleService roleService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDepartRoleService departRoleService;

    @Autowired
    private SysUserDepartService sysUserDepartService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysDepartRoleUserService departRoleUserService;

    @Override
    public void updateUserDepart(String username, String orgCode) {
        this.baseMapper.updateUserDepart(username, orgCode);
    }

    @Override
    public List<String> getRole(String username) {
        return roleService.getRoleByUserName(username);
    }

    @Override
    public IPage<SysUser> queryPageList(SysUserModel model) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(model.getDepartId())) {
            LambdaQueryWrapper<SysUserDepart> query = new LambdaQueryWrapper<>();
            query.eq(SysUserDepart::getDepId, model.getDepartId());
            List<SysUserDepart> list = sysUserDepartService.list(query);
            List<String> userIds = list.stream().map(SysUserDepart::getUserId).collect(Collectors.toList());
            wrapper.lambda().in(SysUser::getId, userIds);
        }
        //用户ID
        if (StringUtils.isNotEmpty(model.getCode())) {
            wrapper.lambda().in(SysUser::getId, Arrays.asList(model.getCode().split(",")));
            model.setPageSize(model.getCode().split(",").length);
        }
        if(StringUtils.isNotEmpty(model.getStatus())){
            wrapper.lambda().eq(SysUser::getStatus, Integer.parseInt(model.getStatus()));
        }
        if(StringUtils.isNotEmpty(model.getPhone())){
            wrapper.lambda().eq(SysUser::getPhone, model.getPhone());
        }
        if(StringUtils.isNotEmpty(model.getRealname())){
            wrapper.lambda().eq(SysUser::getRealname, model.getRealname());
        }
        if(StringUtils.isNotEmpty(model.getSex())){
            wrapper.lambda().eq(SysUser::getSex, model.getSex());
        }
        if(StringUtils.isNotEmpty(model.getUsername())){
            wrapper.lambda().like(SysUser::getUsername, model.getUsername());
        }
        if (model.getOrder().toUpperCase().indexOf("ASC")>=0) {
            String columnStr = StringUtils.camelToUnderline(model.getColumn());
            String[] columnArray = columnStr.split(",");
            wrapper.orderByAsc(columnArray);
        } else {
            String columnStr = StringUtils.camelToUnderline(model.getColumn());
            String[] columnArray = columnStr.split(",");
            wrapper.orderByDesc(columnArray);
        }
        Page<SysUser> page = new Page<SysUser>(model.getPageNo(), model.getPageSize());
        IPage<SysUser> pageList = this.baseMapper.selectPage(page, wrapper);
        List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item -> {
                item.setOrgCode(useDepNames.get(item.getId()));
            });
        }
        return pageList;
    }

    @Override
    public Map<String, String> getDepNamesByUserIds(List<String> userIds) {
        List<SysUserDepModel> list = this.baseMapper.getDepNamesByUserIds(userIds);
        Map<String, String> res = new HashMap<String, String>();
        list.forEach(item -> {
                    if (res.get(item.getUserId()) == null) {
                        res.put(item.getUserId(), item.getDepartName());
                    } else {
                        res.put(item.getUserId(), res.get(item.getUserId()) + "," + item.getDepartName());
                    }
                }
        );
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(SysUserDto user) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user, sysUser);
        sysUser.setId(String.valueOf(SnowflakeIdUtil.nextId()));
        sysUser.setCreateTime(LocalDateTime.now());//设置创建时间
        String salt = StringUtils.randomGen(8);
        sysUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        sysUser.setPassword(passwordEncode);
        sysUser.setStatus(1);
        sysUser.setDelFlag(CommonConstants.DEL_FLAG_0);
        sysUser.setCreateBy(BaseContextHandler.getUsername());
        sysUser.setUpdateBy(BaseContextHandler.getUsername());
        //step.1 保存用户
        int save = this.baseMapper.insert(sysUser);
        //step.2 保存角色
        if (StringUtils.isNotEmpty(user.getSelectedroles())) {
            String[] arr = user.getSelectedroles().split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole().setRoleId(roleId).setUserId(sysUser.getId());
                boolean role = roleService.save(userRole);
            }
        }
        //step.3 保存所属部门
        if (StringUtils.isNotEmpty(user.getSelecteddeparts())) {
            String[] arr = user.getSelecteddeparts().split(",");
            for (String deaprtId : arr) {
                SysUserDepart userDeaprt = new SysUserDepart().setUserId(sysUser.getId()).setDepId(deaprtId);
                boolean depart = sysUserDepartService.save(userDeaprt);
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editUser(SysUser sysUser, String roles, String departs) {
        int update = this.baseMapper.updateById(sysUser);
        //step.2 修改角色
        //处理用户角色 先删后加

        boolean b = roleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,sysUser.getId()));//.removeById(sysUser.getId());
        if (StringUtils.isNotEmpty(roles)) {
            String[] arr = roles.split(",");
            for (String roleId : arr) {
                SysUserRole userRole = new SysUserRole().setUserId(sysUser.getId()).setRoleId(roleId);
                roleService.save(userRole);
            }
        }
        //step.3 修改部门
        String[] arr = {};
        if (StringUtils.isNotEmpty(departs)) {
            arr = departs.split(",");
        }

        //查询已关联部门
        List<SysUserDepart> userDepartList = sysUserDepartService.list(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, sysUser.getId()));
        if (userDepartList != null && userDepartList.size() > 0) {
            for (SysUserDepart depart : userDepartList) {
                //修改已关联部门删除部门用户角色关系
                if (!Arrays.asList(arr).contains(depart.getDepId())) {
                    List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().lambda().eq(SysDepartRole::getDepartId, depart.getDepId()));
                    List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
                    if (roleIds != null && roleIds.size() > 0) {
                        departRoleUserService.remove(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, sysUser.getId())
                                .in(SysDepartRoleUser::getDroleId, roleIds));

                    }
                }
            }
        }
        //先删后加
        sysUserDepartService.remove(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, sysUser.getId()));
        if (StringUtils.isNotEmpty(departs)) {
            for (String departId : arr) {
                SysUserDepart userDepart = new SysUserDepart().setUserId(sysUser.getId()).setDepId(departId);
                sysUserDepartService.save(userDepart);
            }
        }
        return true;
    }

    @Override
    public Boolean changePassword(SysUser sysUser) {
        String salt = StringUtils.randomGen(8);
        sysUser.setSalt(salt);
        String password = sysUser.getPassword();
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
        sysUser.setPassword(passwordEncode);
        int i = this.baseMapper.updateById(sysUser);
        return i > 0;
    }

    @Override
    public List<SysUser> deletelist() {
        return this.baseMapper.deletelist();
    }

    @Override
    public Boolean revertLogicDeleted(List<String> userIds, SysUser updateEntity) {
        String ids = String.format("'%s'", String.join("','", userIds));
        return this.baseMapper.revertLogicDeleted(ids, updateEntity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteRecycleBin(List<String> userIds) {
        String ids = String.format("'%s'", String.join("','", userIds));
        // 1. 删除用户
        this.baseMapper.deleteLogicDeleted(ids);
        // 2. 删除用户部门关系
        sysUserDepartService.remove(new LambdaQueryWrapper<SysUserDepart>().in(SysUserDepart::getUserId, userIds));
        //3. 删除用户角色关系
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));
        return true;
    }

    @Override
    public IPage<SysUser> getUserByRoleId(Page<SysUser> page, RoleModel model) {
        return this.baseMapper.getUserByRoleId(page,model.getRoleId(),model.getUsername());
    }

    @Override
    public IPage<SysUser> getUserByDepIds(Page<SysUser> page, List<String> subDepids, String username) {
        return this.baseMapper.getUserByDepIds(page, subDepids,username);
    }

    @Override
    public IPage<SysUserSysDepartModel> queryUserByOrgCode(AddressListModel model) {
        List<SysUserSysDepartModel> list = this.baseMapper.getUserByOrgCode(new Page(model.getPageNo(), model.getPageSize()), model);
        Integer total = this.baseMapper.getUserByOrgCodeTotal(model);
        IPage<SysUserSysDepartModel> result = new Page<>(model.getPageNo(), model.getPageSize(), total);
        result.setRecords(list);
        return result;
    }


}
